﻿@{
    ViewBag.Title = "Scheduler";
}

<script>
    var currentButton;
    var currentDivId = '';
    var currentTD;
    var intervalID;
    var prevTable;

    function cancelBuilding() {
        window.clearInterval(intervalID);
        document.getElementById('scheduleTable').innerHTML = prevTable;
    }

    var flag = true;
    function changeColor() {
        if (flag == true) {

            $('td').filter(function () {
                return (this.innerHTML != '' && $(this).data("status") != "selected" && $(this).data("status") != "hidden");
            }).each(function () { var $this = $(this); $this.data('bgcolor', $this.css('background-color')); $this.css('background-color', 'transparent'); });
            flag = false;
        }
        else if (flag == false) {
            $('td').filter(function () {
                return this.innerHTML != '';
            }).each(function () { var $this = $(this); $this.css('background-color', $this.data('bgcolor')); });
            flag = true;
        }
    }

    function hashCode(str) { // java String#hashCode
        var hash = 0;
        for (var i = 0; i < str.length; i++) {
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }
        return hash;
    }

    function intToARGB(i) {
        return ((i >> 24) & 0xFF).toString(16) +
               ((i >> 16) & 0xFF).toString(16) +
               ((i >> 8) & 0xFF).toString(16) +
               (i & 0xFF).toString(16);
    }

    function performOp(divId, button) {
        if (currentDivId != '') {
            document.getElementById(currentDivId).style.display = "none";
            currentButton.style.border = "none";
            currentButton.style.borderColor = "none";

            if (currentDivId == 'colorsBox') {
                document.getElementById('scheduleTable').style.cursor = "default";
                if (currentTD != null) {
                    if (currentTD.id != 'noColor') {
                        currentTD.style.border = 'none';
                    } else {
                        currentTD.style.border = 'dotted';
                    }
                }
                currentTD = null;
            }
            if (currentDivId == 'buildMode') {
                cancelBuilding();
            }
        }
        if (divId == currentDivId) {
            currentDivId = '';
            currentButton = null;
            return;
        }
        else {
            currentDivId = divId;
            currentButton = button;
            button.style.border = "solid";
            button.style.borderColor = "purple";
            document.getElementById(divId).style.display = "block";
        }
        if (divId == 'facebookGroup') {
            collectFacebookGroups(course2color, 'facebookGroup');
        }
        if (divId == 'buildMode') {
            prevTable = document.getElementById('scheduleTable').innerHTML;
            var courses = new Array();
            //Bring all groups of all courses:
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var j = JSON.parse(xmlhttp.responseText);

                    //Build courses list
                    for (var i = 0; i < j.count; i++) {
                        var isInArray = false;
                        for (var k = 0; k < courses.length; k++) {
                            if (j.jsonGroups[i].cname == courses[k].cname) {
                                isInArray = true;
                            }
                        }
                        if (isInArray == false) {
                            courses.push(j.jsonGroups[i]);
                        }
                    }
                    var colors = ["blue", "green", "yellow", "orange", "#FF00FF", "#FFFFFF", "CC9933", "black", "white"];
                    var colorIndex = 0;
                    for (var c in courses) {
                        var roles = new Array();
                        //find the possible roles of this course's groups
                        var groups = j.jsonGroups;
                        for (g = 0; g < groups.length; g++) {
                            if (courses[c].cname == groups[g].cname) {
                                var isInArray = false;
                                for (var i = 0; i < roles.length; i++) {
                                    if (roles[i] == groups[g].r) {
                                        isInArray = true;
                                    }
                                }
                                if (isInArray == false) {
                                    roles.push(groups[g].r);
                                }
                            }
                        }
                        //for each role find related group and color it with unique color for the role+course
                        for (var r = 0; r < roles.length; r++) {
                            //alert('course number:' + courses[c].cnum + ' name:' + courses[c].cname + ' role:' + roles[r]);
                            var groups = j.jsonGroups;
                            for (var g = 0; g < groups.length; g++) {
                                if (courses[c].cname == groups[g].cname && groups[g].r == roles[r]) {
                                    groups[g].color = colors[colorIndex];
                                }
                            }
                            colorIndex++;
                        }
                        colorIndex++;
                    }

                    table = document.getElementById("scheduleTable");

                    //delete previous table
                    table.innerHTML = "";
                    //build header
                    var header = table.insertRow(0);
                    var cell = document.createElement('th');
                    cell.innerHTML = "Hour/Day";
                    cell.style.border = "solid";
                    header.appendChild(cell);
                    for (var k = 1; k < 7; k++) {
                        var cell = document.createElement('th');
                        cell.innerHTML = days[k - 1];
                        cell.style.border = "solid";
                        header.appendChild(cell);
                    }

                    //create all the cells and print the hours
                    for (var k = 1; k < 29; k += 2) {
                        var row = table.insertRow(k);
                        var cell = document.createElement('td');
                        x = Math.floor(k / 2) + 7;
                        hour = x.toString();
                        cell.innerHTML = hour + ".0";
                        cell.style.border = "solid";
                        row.appendChild(cell);

                        for (var l = 1; l < 7; l++) {
                            var cell = document.createElement('td');
                            cell.id = (k * 7 + l + 1);
                            cell.style.border = "solid";
                            row.appendChild(cell);
                        }

                        var row = table.insertRow(k + 1);
                        var cell = document.createElement('td');
                        cell.innerHTML = hour + ".3";
                        cell.style.border = "solid";
                        row.appendChild(cell);

                        for (var l = 1; l < 7; l++) {
                            var cell = document.createElement('td');
                            cell.id = (k + 1) * 7 + l + 1;
                            cell.style.border = "solid";
                            row.appendChild(cell);
                        }
                    }


                    //Fill in the table:
                    for (i = 0; i < j.jsonGroups.length; i++) {
                        var rowIndex = (parseInt(j.jsonGroups[i].start) - 7) * 2 + 1;
                        //check if it 17:00 or 17:30
                        if (parseFloat(j.jsonGroups[i].start) - rowIndex) {
                            rowIndex += 1;
                        }
                        var id = parseInt(j.jsonGroups[i].day) + 1 + 1 + rowIndex * 7;
                        var td = document.getElementById(id);
                        td.setAttribute("align", "center");
                        td.innerHTML = "<a href= '/Courses/Info/?number=  " + j.jsonGroups[i].cnum.toString()
                                       + "'>" + j.jsonGroups[i].cname + "</a>" + "<br>"
                                       + j.jsonGroups[i].r + " " + j.jsonGroups[i].gnum;
                        //alert("#"+intToARGB(hashCode("abcd")));
                        td.style.backgroundColor = j.jsonGroups[i].color;
                        rowspan = parseFloat(j.jsonGroups[i].duration) * 2;
                        td.setAttribute("rowspan", rowspan);
                        for (var t = 1; t < rowspan; t++) {
                            td = document.getElementById((t * 7) + id);
                            td.parentNode.removeChild(td);
                        }
                    }


                    //Manual Building functionality:
                    $('td').filter(function () {
                        return this.innerHTML != '';
                    }).click(function () {
                        var $this = $(this);
                        var $courseName = $this.find("a").first().text();
                        var $courseRole = $this.html().split("<br>")[1].replace(/\d+/g, '');
                        //alert($courseRole);
                        if ($this.data("status") == "selected") {
                            $this.data("status", "");
                            $('td').filter(function () {
                                return ($(this).data("family") == ("bro" + $this.attr('id')));
                            }).each(function () {
                                $(this).data("status", "");
                                $(this).data("family", "");
                                $(this).html($(this).data('content'));
                                $(this).css('background-color', $this.data('bgcolor'));
                                $(this).attr("rowspan", $(this).data('span'));
                                $('.spantd' + $this.attr('id')).remove();
                            });
                        }
                        else if ($this.data("status") != "hidden") {
                            $this.data("status", "selected");
                            $this.css('background-color', $this.data('bgcolor'));
                            $('td').filter(function () {
                                return ($(this).data("status") != "selected" && this.innerHTML.toString().indexOf($courseName) != -1 && this.innerHTML.toString().indexOf($courseRole) != -1);
                            }).each(function () {
                                $(this).data("status", "hidden");
                                $(this).data("family", "bro" + $this.attr('id'));
                                $(this).data("content", $(this).html());
                                $(this).html('');
                                $(this).css('background-color', 'transparent');
                                $(this).data('span', $(this).attr("rowspan"));
                                $(this).attr("rowspan", 1);
                                var $col = $(this).parent().children().index($(this));
                                //alert($col);
                                var $row = $(this).parent().parent().children().index($(this).parent());
                                var $j = $(this).parent('tr').next();
                                var $k = $j.find("td:nth-child(" + $col + ")");
                                for (var i = 0; i < $(this).data('span') - 1 ; i++) {
                                    $k.after("<td class='spantd" + $this.attr('id') + "' style='border: solid;'>");
                                    $j = $j.next();
                                    $k = $j.find("td:nth-child(" + $col + ")");
                                }
                            });
                        }
                    });

                    intervalID = setInterval("changeColor()", 1000);
                }
            }
            xmlhttp.open("GET", "/Courses/MyGroups/", true);
            xmlhttp.send();
        }
    }

    function fill(td) {
        if (currentTD != null) {
            if (currentTD.id != 'noColor') {
                currentTD.style.border = 'none';
            } else {
                currentTD.style.border = 'dotted';
            }
        }
        currentTD = td;
        document.getElementById('scheduleTable').style.cursor = "pointer";
        td.style.border = 'solid';
    }

    $(document).ready(function () {
        $('#scheduleTable').on('click', 'td', function () {
            if (currentTD != null) {
                if (currentTD.id != 'noColor') {
                    $(this).css('background-color', currentTD.style.backgroundColor);
                } else {
                    $(this).css('background-color', 'transparent');
                }
            }
        });
    });


</script>

<h2>Scheduler</h2>
After you chose your courses, it is the time to set the constraints and invoke the automatic scheduler. <br />

<aside>
    <span>
        <div id="fb-root"></div>
        <fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
    </span> <br /><br />
    <span id="signinButton">
        <span class="g-signin"
              data-callback="signinCallback"
              data-clientid="265964925788-isfopjfsn7udo115ffal1d3j793sar11.apps.googleusercontent.com"
              data-cookiepolicy="single_host_origin"
              data-requestvisibleactions="http://schemas.google.com/AddActivity"
              data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar">
        </span>
    </span> <br />
    <h4> <a id="signoutLink" href="javascript:disconnectUser(gapi.auth.getToken().access_token);" style="visibility: hidden">signout</a> </h4> <br />

    <br />
</aside>

<ol class="round">
    <li class="one" id="groupsLi">
        <h5>Group Constraints</h5>
        You can specify which groups you want and which you don't.
        <a href="javascript:void(0)" id="groupsLink" onclick="loadGroups();">>></a>
        <img id="gWait" style="display:none;" src="../../Images/wait.gif" />
        <div id="groupsList">
        </div>
    </li>
    <li class="two">
        <h5>No running</h5>
        <input type="checkbox" onclick="noRunningClicked();"> Make sure you don't have to run between buildings during a 10-minute break. </input>
    </li>
    <li class="three" id="freeDaysLi">
        <h5>Free days</h5>
        Exclude days/hours from studying
        <a href="javascript:void(0)" id="freeDaysLink" onclick="loadFreeDays();">>></a>
        <div id="freeDaysList">
        </div>
    </li>
    <li class="four" id="scheduleLi">
        <h5>Schedules</h5>
        Show a schedule table of your selected courses
        <br />
        <div id="noOverlapping" style="visibility:visible">
        </div> <br \>
        <img id="sWait" style="display:none;" src="../../Images/wait.gif" />
        <div id="scheduleNum" style="visibility:visible">  </div> <br \>
        <img src="../../Images/save.png" title="Save" onclick="save(useremail);" style="width:40px;" />
        &nbsp <img src="../../Images/build.ico" title="Go into build mode" onclick="performOp('buildMode',this);" style="width:40px;" />
        &nbsp <img style="width:40px;" src="../../Images/calculator.ico" title="Do Average Calculations" onclick="" />
        &nbsp  <img style="width:40px;" src="../../Images/maps.ico" title="Find Course's Location in Google Map" onclick="performOp('googleMaps',this);" />
        &nbsp <img style="width:40px;" src="../../Images/fill.ico" title="Fill in the table with colors as you like" onclick="performOp('colorsBox',this);" />
        <a target="_blank" id="largeView"><img src="../../Images/link.ico" title="Generate a Link to the table" style="width:40px;" /></a>
        &nbsp <img src="../../Images/facebookgroupicon.jpg" style="width:40px;" title="Join the facebook groups of the selected courses" onclick="performOp('facebookGroup',this);" />
        &nbsp <img src="../../Images/googleCalendar.ico" style="width:40px;" title="Sync with google calendar" onclick="syncWithGoogleCalendar();" />
        &nbsp <img src="../../Images/down-arrow-download-icone-3675-64.png" style="width:40px;" title="Get ICAL" onclick="getICAL();" />
         <br />
        <div id="googleMaps" style="display:none;border:solid;border-color:purple;">
            <div id="mapDiv"></div>
            <div id="map-canvas" style="height:200px"></div>
        </div>
        <br />
        <div id="facebookGroup" style="display:none;border:solid;border-color:purple;"></div>
        <div id="buildMode" style="display:none;border:solid;border-color:purple;">
            <br />
            Click on the flashing group you want to select. In order to unselect it, click on it and you see all other related groups for this course back to flash.
            <br /><br />
            <button>Save</button>&nbsp<button onclick="performOp('buildMode',this);">Cancel</button>
        </div>
        <div id="colorsBox" style="display:none;border:solid;border-color:purple;">
            <br />
            Pick a color and fill in any cell in the table:
            &nbsp
            <table id="colorsTable" style="height:30px;cursor:pointer;">
                <tbody>
                    <tr>
                        <td style="background-color:#c00000" onclick="fill(this);"></td>
                        <td style="background-color:#ff0000" onclick="fill(this);"></td>
                        <td style="background-color:#ffc000" onclick="fill(this);"></td>
                        <td style="background-color:#ffff00" onclick="fill(this);"></td>
                        <td style="background-color:#92d050" onclick="fill(this);"></td>
                        <td style="background-color:#00b050" onclick="fill(this);"></td>
                        <td style="background-color:#00b0f0" onclick="fill(this);"></td>
                        <td style="background-color:#0070c0" onclick="fill(this);"></td>
                        <td style="background-color:#002060" onclick="fill(this);"></td>
                        <td style="background-color:#7030a0" onclick="fill(this);"></td>
                        <td id="noColor" style="border:dotted" onclick="fill(this);"></td>
                    </tr>
                </tbody>
            </table>
            <br />
        </div>
        <br />
        <img src="../../Images/prev2.ico" title="Show Prev Schedule" onclick="loadScheduleTable(1);" /> &nbsp
        <img src="../../Images/next.ico" title="Show Next Schedule" onclick="loadScheduleTable(2);" /> &nbsp
        | &nbsp
        <input type="checkbox" onclick="noOverlappingClicked();"> Hide overlapping &nbsp
        | &nbsp
        <input id="rankNum" style="width:30px;" onkeypress="Javascript: if (event.keyCode==13) {loadScheduleTable(5);}" />
        &nbsp Out of &nbsp <span id="maxRank"></span>
        <br />
        <table id="scheduleTable"></table>
    </li>
    <li class="six" id="examsLi">
        <h5>Exams Table</h5>
        Show exams table of your selected courses
        <a href="javascript:void(0)" id="examslink" onclick="loadExamsTable();">>></a>
        @*TODO: Replace the current table with more beautiful one*@
        <img id="eWait" style="display:none;" src="../../Images/wait.gif" />
        <table id="examsTable"></table>
    </li>
</ol>

